<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2021/3/16
 * Time: 上午11:19
 */

namespace App\Models\CacheModel;

use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

/**
 * 用户访问记录模型
 * @support v2.5.3
 * @desc 用户神策用户首次访问is_first打点
 * Class ZlVisit
 * @package App\Models\CacheModel
 */
class ZlVisit extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_visit';

    protected $cacheModel = 'user.visit';

    /**
     * 写入首次访问记录
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function SaveData($data)
    {
        try
        {
            $this->save($data);
        }
        catch (\Exception $e)
        {
            Log::write('添加访问记录失败：' . $e->getMessage() . '[ ' . $e->getFile() . '：' . $e->getLine() . ' ]', 'error', true);
            return false;
        }
        $key = $data['uid'] . ':' . $data['type'];
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $key)->rmCache();
        return true;
    }


    /**
     * @param $uid int 用户id
     * @param $type int 功能类型 1:校准生辰,2:幸运之城,3:提问,
     * @return int 0 => 非首次访问  1 =》 首次访问
     */
    public function getVisitData($uid, $type): int
    {

        $res = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid . ':' . $type)->getDataAndSet(function () use ($uid, $type)
        {
            try
            {
                $data = $this->where(['uid' => $uid, 'type' => $type])->field('id')->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                $data = ['id' => 0];
            }
            return $data;
        });
        $insertStatus = false;
        if ($res['id'] === 0)
        {
            $data = [
                'uid' => $uid,
                'type' => $type,
                'create_time' => time(),
            ];
            $insertStatus = $this->SaveData($data);
        }
        return ((int)$res['id'] === 0 && $insertStatus) ? 1 : 0;
    }
}
